import 'package:flutter/material.dart';
import 'package:gksz/political_Theory/Recommend/MessagePage/MessagePage.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

Dio dio = new Dio();

class Study extends StatefulWidget {
  Study({Key key}) : super(key: key);
  _StudyState createState() => _StudyState();
}

class _StudyState extends State<Study> {
  Widget build(BuildContext context) {
    return Scaffold(
      body: StudyList(),
    );
  }
}

class StudyList extends StatefulWidget {
  @override
  StudyListState createState() {
    return StudyListState();
  }
}

class StudyListState extends State<StudyList> {
  List<String> items = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
  ];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1500));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
    message();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(seconds: 1));
    if (items.length < _res.length) {
      items.add((items.length + 1).toString());
    }
    // if failed,use loadFailed(),if no data return,use LoadNodata()

    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return _res == null
        ? Center(
          child: Container(
          width: 100.0,
          height: 100.0,
          decoration: BoxDecoration(
            color: Colors.grey,
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            CircularProgressIndicator(),
            Container(height: 10.0,),
            Text('正在加载...',style: TextStyle(fontSize: 16.0,color: Colors.white),)
          ],
        ),
        ),
        )
        :  Scaffold(
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: ClassicHeader(
          height: 45.0,
          releaseText: '松开手刷新',
          refreshingText: '刷新中',
          completeText: '刷新完成',
          failedText: '刷新失败',
          idleText: '下拉刷新',
        ),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("已经到底了");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！单击“重试”");
            } else {
              body = Text("上拉加载");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: _headerView(),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    getName();
    missionpoint();
    message();
  }

  var _point;
  void missionpoint() async {
    if (number.length == 10) {
      Response response = await dio.get(
          'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${this.user_id}');
      _point = response.data;
    } else {
      Response response = await dio.get(
          'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${this.user_id}');
      _point = response.data;
    }
    setState(() {});
  }

  var user_id;
  var number;
  getName() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    user_id = sharedPreferences.getString('user_id');
    number = sharedPreferences.getString('number');
    missionpoint();
    setState(() {});
  }

  var _res;
  void message() async {
    Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/news?query={"type":"学习"}&sort=-createdAt');
    _res = response.data;
    setState(() {});
  }

  Widget _headerView() {
    return _res.length==0 
        ? Center(
            child: Image.asset('images/nomessage.png'),
          ):
                 CustomScrollView(
            physics: new BouncingScrollPhysics(),
            slivers: <Widget>[
              new SliverList(
                delegate: new SliverChildBuilderDelegate((ctx, index) {
                  if (_res.length < 6) {
                    items.length = _res.length;
                  }
                  return Container(
                      child: ListView.builder(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemCount: items.length,
                    itemBuilder: (context, index) {
                      Widget title;
                      if ('${_res[index]['album']}' != '') {
                        title = Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              width: MediaQuery.of(context).size.width - 150,
                              child: Text(
                                "${_res[index]['title']}",
                                style: TextStyle(fontSize: 16.0),
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Container(
                              width: 100,
                              height: 75,
                              margin: EdgeInsets.only(left: 10, top: 5),
                              child: Image.network(
                                '${_res[index]['album']}',
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                        );
                      } else {
                        title = Text(
                          "${_res[index]['title']}",
                          style: TextStyle(fontSize: 16.0),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        );
                      }
                      return Column(
                        children: <Widget>[
                          Container(
                              padding: EdgeInsets.all(0),
                              // width: MediaQuery.of(context).size.width,
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom: BorderSide(
                                          width: 1, color: Color(0xffe5e5e5)))),
                              child: ListTile(
                                title: title,
                                subtitle: Column(
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Container(
                                          child: Text("${_res[index]['from']}",
                                              style: TextStyle(fontSize: 13.0)),
                                        ),
                                        Container(
                                          child: Text(
                                              "${_res[index]['createdAt'].substring(0, 10)}",
                                              style: TextStyle(fontSize: 13.0)),
                                          width: 100.0,
                                          height: 25.0,
                                          alignment: Alignment.center,
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                onTap: () async {
                                  print(this._point['mission']['study']);
                                  if (this._point['number'].length == 10) {
                                    if (this._point['mission']['study'] ==
                                        'false') {
                                      var newpoint = this._point['point'] + 1;
                                      var pp = await dio.patch(
                                          'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${user_id}',
                                          data: {'point': newpoint});
                                      var zhuangtai = await dio.patch(
                                          'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${user_id}',
                                          data: {
                                            "mission": {
                                              "study": "true",
                                            }
                                          });
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) => MessagePage(
                                                  msg: _res[index])));
                                    } else {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) => MessagePage(
                                                  msg: _res[index])));
                                    }
                                  } else {
                                    if (this._point['mission']['study'] ==
                                        'false') {
                                      var newpoint = this._point['point'] + 1;
                                      var pp = await dio.patch(
                                          'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${user_id}',
                                          data: {'point': newpoint});
                                      var zhuangtai = await dio.patch(
                                          'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${user_id}',
                                          data: {
                                            "mission": {
                                              "study": "true",
                                            }
                                          });
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) => MessagePage(
                                                  msg: _res[index])));
                                    } else {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) => MessagePage(
                                                  msg: _res[index])));
                                    }
                                  }
                                },
                              )),
                        ],
                      );
                    },
                  ));
                }, childCount: 1),
              ),
            ],
          );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}
